package com.wxsong.authplatform.authweb.util;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class ObjectUtil {

    public static Map toMap(Object object) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if(object == null){
            return Maps.newHashMap();
        }
        Map map = Maps.newHashMap();
        Class clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (int i=0; i<fields.length; i++){
            Field field = fields[i];
            String fieldName = field.getName();
            String getMethodName = "get"+ lowerCharToUpper(fieldName,0);
            Object res = clazz.getMethod(getMethodName, null).invoke(object);
            System.out.println(getMethodName + "==========" + res);
            map.put(fieldName, res);
        }

        return map;
    }

    public static String lowerCharToUpper(String str, int index){
        if(StringUtils.isBlank(str)){
            return str;
        }
        char[] ch = str.toCharArray();
        ch[index] -= 32;
        return new String(ch);
    }

//    public static void main(String[] args) {
////        String aaa = "name";
////        char[] ch = aaa.toCharArray();
////        ch[2] -= 32;
////        String bbb = new String(ch);
////        System.out.println(bbb);
//        Role user = new Role("nihao");
//        Map map = null;
//        try {
//            map = toMap(user);
//        } catch (NoSuchMethodException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
//
//        System.out.println("============");
//    }
}
